package com.example.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.domain.User;
import com.example.demo.entity.Messages;
import com.example.demo.service.MessagesService;
import com.example.demo.service.UserService;
import com.example.demo.utils.Result;
import com.example.demo.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/message")
@RequiredArgsConstructor
@CrossOrigin
@Slf4j
public class MessageController {

    private final MessagesService messagesService;
    private final UserService userService;

    /**
     * 获取聊天记录
     * @param request HTTP请求
     * @param receiverId 接收者ID
     * @param isGroup 是否为群聊
     * @return 聊天记录列表
     */
    @GetMapping("/getMessage")
    public Result<List<Messages>> getMessage(HttpServletRequest request, 
                                            @RequestParam String receiverId, 
                                            @RequestParam(defaultValue = "false") String isGroup) {
        // 验证token
        String token = request.getHeader("authorization");
        log.info("接收到getMessage请求 - receiverId: {}, isGroup: {}, token是否为空: {}", 
                receiverId, isGroup, !StringUtils.hasText(token));
        
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        // 验证参数
        if (!StringUtils.hasText(receiverId)) {
            return Result.error("接收者ID不能为空");
        }
        
        // 确保receiverId是有效的数字
        try {
            Long.parseLong(receiverId);
        } catch (NumberFormatException e) {
            log.error("接收者ID格式错误: {}", receiverId, e);
            return Result.error("接收者ID必须是有效的数字");
        }
        
        // 调用服务获取消息
        List<Messages> messages = messagesService.getMessage(token, receiverId, isGroup);
        log.info("查询到消息数量: {}", messages.size());
        
        return Result.success(messages);
    }

    /**
     * 发送消息
     * @param messages 消息对象
     * @param request HTTP请求
     * @return 发送结果
     */
    @PostMapping("/sendMessage")
    public Result<String> sendMessage(@RequestBody Messages messages, HttpServletRequest request) {
        // 验证token
        String token = request.getHeader("authorization");
        log.info("接收到sendMessage请求 - receiverId: {}, content: {}, token是否为空: {}", 
                messages != null ? messages.getReceiverId() : null, 
                messages != null ? messages.getContent() : null,
                !StringUtils.hasText(token));
        
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        // 验证消息内容
        if (messages == null || !StringUtils.hasText(messages.getContent())) {
            return Result.error("消息内容不能为空");
        }
        
        // 验证接收者ID
        if (messages.getReceiverId() == null) {
            return Result.error("接收者ID不能为空");
        }
        
        // 发送消息
        String result = messagesService.sendMessage(token, messages);
        log.info("发送消息结果: {}", result);
        
        return Result.success(result);
    }
    
    /**
     * 获取最近的聊天记录
     * @param request HTTP请求
     * @param receiverId 接收者ID
     * @param isGroup 是否为群聊
     * @param limit 限制条数
     * @return 最近的聊天记录列表
     */
    @GetMapping("/getRecentMessages")
    public Result<List<Messages>> getRecentMessages(HttpServletRequest request, 
                                                  @RequestParam String receiverId, 
                                                  @RequestParam(defaultValue = "false") String isGroup,
                                                  @RequestParam(defaultValue = "20") Integer limit) {
        // 验证token
        String token = request.getHeader("authorization");
        log.info("接收到getRecentMessages请求 - receiverId: {}, isGroup: {}, limit: {}", 
                receiverId, isGroup, limit);
        
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        // 验证参数
        if (!StringUtils.hasText(receiverId)) {
            return Result.error("接收者ID不能为空");
        }
        
        // 确保receiverId是有效的数字
        try {
            Long.parseLong(receiverId);
        } catch (NumberFormatException e) {
            log.error("接收者ID格式错误: {}", receiverId, e);
            return Result.error("接收者ID必须是有效的数字");
        }
        
        if (limit <= 0 || limit > 100) {
            limit = 20; // 默认限制20条
        }
        
        // 获取消息
        List<Messages> messages = messagesService.getMessage(token, receiverId, isGroup);
        log.info("查询到消息数量: {}", messages.size());
        
        // 如果消息数量超过limit，只返回最近的limit条
        if (messages.size() > limit) {
            messages = messages.subList(messages.size() - limit, messages.size());
            log.info("限制消息数量为: {}", limit);
        }
        
        return Result.success(messages);
    }
    
    /**
     * 获取未读消息数量
     * @param request HTTP请求
     * @return 未读消息数量Map，key为发送者ID，value为未读消息数量
     */
    @GetMapping("/getUnreadCount")
    public Result<Map<String, Integer>> getUnreadMessageCount(HttpServletRequest request) {
        // 验证token
        String token = request.getHeader("authorization");
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        return Result.success(messagesService.getUnreadMessageCount(token));
    }
    
    /**
     * 将消息标记为已读
     * @param request HTTP请求
     * @param senderId 发送者ID
     * @return 操作结果
     */
    @PostMapping("/markAsRead")
    public Result<String> markMessagesAsRead(HttpServletRequest request, @RequestParam String senderId) {
        // 验证token
        String token = request.getHeader("authorization");
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        // 验证参数
        if (!StringUtils.hasText(senderId)) {
            return Result.error("发送者ID不能为空");
        }
        
        // 确保senderId是有效的数字
        try {
            Long.parseLong(senderId);
        } catch (NumberFormatException e) {
            return Result.error("发送者ID必须是有效的数字");
        }
        
        return Result.success(messagesService.markMessagesAsRead(token, senderId));
    }
    
    /**
     * 测试接口 - 直接查询所有消息
     * @return 所有消息列表
     */
    @GetMapping("/testAllMessages")
    public Result<List<Messages>> testAllMessages() {
        LambdaQueryWrapper<Messages> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Messages::getCreateTime);
        List<Messages> messages = messagesService.list(wrapper);
        
        log.info("测试查询所有消息 - 总数: {}", messages.size());
        for (Messages msg : messages) {
            log.info("消息: id={}, senderId={}, receiverId={}, content={}, isGroup={}", 
                    msg.getId(), msg.getSenderId(), msg.getReceiverId(), msg.getContent(), msg.getIsGroup());
        }
        
        return Result.success(messages);
    }
    
    /**
     * 测试接口 - 查询指定用户之间的消息
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @return 消息列表
     */
    @GetMapping("/testUserMessages")
    public Result<List<Messages>> testUserMessages(@RequestParam Long senderId, @RequestParam Long receiverId) {
        LambdaQueryWrapper<Messages> wrapper = new LambdaQueryWrapper<>();
        wrapper.nested(w -> w
                .nested(n -> n.eq(Messages::getSenderId, senderId).eq(Messages::getReceiverId, receiverId))
                .or()
                .nested(n -> n.eq(Messages::getSenderId, receiverId).eq(Messages::getReceiverId, senderId))
            )
            .orderByAsc(Messages::getCreateTime);
        
        List<Messages> messages = messagesService.list(wrapper);
        
        log.info("测试查询用户消息 - senderId: {}, receiverId: {}, 总数: {}", 
                senderId, receiverId, messages.size());
        
        for (Messages msg : messages) {
            log.info("消息: id={}, senderId={}, receiverId={}, content={}, isGroup={}", 
                    msg.getId(), msg.getSenderId(), msg.getReceiverId(), msg.getContent(), msg.getIsGroup());
        }
        
        return Result.success(messages);
    }
}
